package com.powernode.common.feign;

import com.powernode.common.execption.PowerException;
import com.powernode.common.result.Result;
import com.powernode.common.result.ResultCodeEnum;
import feign.FeignException;
import feign.Response;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * 自定义feign decoder，在feign调用结束后统一处理
 */
public class FeignCustomDataDecoder implements Decoder {
    private final SpringDecoder decoder;

    public FeignCustomDataDecoder(SpringDecoder decoder) {
        this.decoder = decoder;
    }

    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        Object object = this.decoder.decode(response, type);
        if (object == null)
            throw new DecodeException(ResultCodeEnum.FEIGN_FAIL.getCode(), ResultCodeEnum.FEIGN_FAIL.getMessage(), response.request());
        if (object instanceof Result<?> result)
            if (result.getCode() != 200)
                throw new PowerException(result.getCode(), result.getMessage());
        return object;
    }
}
